package com.after.saas.file.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Classname ApplicationEventListener
 * @Author hjchen
 * @Date 2023/8/8 17:06
 */
@Slf4j
@Component
public class ApplicationEventListener implements ApplicationListener<ContextClosedEvent> {

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        log.info("spring context closing....");
        ThreadPoolTaskExecutor taskExecutor = event.getApplicationContext().getBean(ThreadPoolTaskExecutor.class);
        //获取spring定时任务调度器
        ThreadPoolTaskScheduler taskScheduler = event.getApplicationContext().getBean(ThreadPoolTaskScheduler.class);
        //获取调度器的执行线程池
        ScheduledThreadPoolExecutor executor = taskScheduler.getScheduledThreadPoolExecutor();
        //停止接收新任务
        executor.shutdown();
        int time = 0;
        while (taskExecutor.getActiveCount() > 0 && time < taskExecutor.getKeepAliveSeconds()) {
            try {
                TimeUnit.SECONDS.sleep(1);
                time++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        log.info("spring context has closed....{}", taskExecutor.getThreadPoolExecutor().isTerminated());
    }
}
